﻿local jwt = require "resty.jwt";

local TokenService = {};

local secret = "nieqiang@01@huashi" -- token密钥

function TokenService.getTokenKey(token)
  jwt:set_alg_whitelist({RS256 = 1, HS256 = 1, HS512 = 1}) -- 设置加密算法白名单
  local jwt_obj = jwt:verify(secret, token); -- token校验

  if not jwt_obj.verified then -- 校验失败
    ngx.log(ngx.ERR, "token签名异常！！！:", jwt_obj.verified);
    ngx.exit(ngx.HTTP_UNAUTHORIZED);
  end

  if jwt_obj.header and jwt_obj.payload then
    local prefix = "login_tokens:";
    local type = jwt_obj.header.type;
    local login_os = jwt_obj.payload.login_os_key;
    local login_username = jwt_obj.payload.login_username_key;
    local login_user = jwt_obj.payload.login_user_key;
    local key = prefix .. type ..":".. login_os ..":".. login_username ..":".. login_user;
    --ngx.log(ngx.INFO, "tokenKey:", key, "jwt_obj:", cjson.encode(jwt_obj));
    return key;
  else
    ngx.log(ngx.ERROR, "令牌解析失败！！！");
    ngx.exit(ngx.HTTP_UNAUTHORIZED);
  end
end

return TokenService;